package com.lyons.easyweb.modular.timer.service.impl;

import org.springframework.stereotype.Service;

import com.lyons.easyweb.exception.BusinessException;
import com.lyons.easyweb.modular.timer.service.TimerExeService;
import com.lyons.easyweb.modular.timer.service.TimerTaskRunner;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class HutoolTimerExeServiceImpl implements TimerExeService {

	@Override
	public void startTimer(String taskId, String cron, String className) {

		if (ObjectUtil.hasEmpty(taskId, cron, className)) {
			log.error("定时任务ID，cron，className为空 ");
			throw new BusinessException(3, "请检查定时器的id，定时器cron表达式，定时任务是否为空！");
		}

		// 预加载类看是否存在此定时任务类
		try {
			Class.forName(className);
		} catch (ClassNotFoundException e) {
			log.error("定时任务指定类不存在。");
			throw new BusinessException(2, "定时任务执行类不存在");
		}

		// 定义hutool的任务
		Task task = () -> {
			try {
				TimerTaskRunner timerTaskRunner = (TimerTaskRunner) SpringUtil.getBean(Class.forName(className));
				timerTaskRunner.action();
			} catch (ClassNotFoundException e) {
				log.error(">>> 任务执行异常：{}", e.getMessage());
			}
		};
		
		// 开始执行任务
		CronUtil.schedule(taskId, cron, task);
	}

	@Override
	public void stopTimer(String taskId) {
		CronUtil.remove(taskId);
	}

}
